package jvlite.render;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import jvlite.core.JLiteContext;
import jvlite.util.JLiteJson;

public class DefaultRender implements IRender {
	/**
	 * standard output by JSON
	 * @param response
	 * @param obj
	 */
	public void renderJSON(HttpServletResponse response, Object obj){
		response.setContentType("application/json");
		try {
			OutputStream outputStream = response.getOutputStream();
			outputStream.write(JLiteJson.self().toJson(obj).getBytes());
			outputStream.flush();
			outputStream.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public void renderFile(HttpServletResponse response, File file){
		try {
			OutputStream os = response.getOutputStream();
			InputStream in = new FileInputStream(file);
			response.addHeader("Content-Disposition", "attachment;filename="
					+ new String(file.getName().getBytes("utf-8"), "utf-8"));
			response.addHeader("Content-Length", file.length() + "");
			response.setContentType("application/x-msdownload");
			int data = 0;
			while ((data = in.read()) != -1) {
				os.write(data);
			}
			os.close();
			in.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public void renderImage(HttpServletResponse response, BufferedImage image){
		response.setHeader("Pragma", "No-cache");
		response.setHeader("Cache-Control", "No-cache");
		response.setDateHeader("Expires", 0);
		response.setContentType("image/png");
		try {
			ServletOutputStream outputStream = response.getOutputStream();
			ImageIO.write(image, "PNG", outputStream);
			outputStream.flush();
			outputStream.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	@Override
	public void renderPage(HttpServletRequest request,HttpServletResponse response,String url, Object data) throws ServletException, IOException {
		request.setAttribute("data", data);	
		request.getRequestDispatcher(url).forward(request, response);
	}

	public void renderError(HttpServletRequest request, HttpServletResponse response) {
		try {
			request.getRequestDispatcher(JLiteContext.errorPath).forward(request, response);
		} catch (ServletException | IOException e) {
			e.printStackTrace();
		}
	}

	@Override
	public void renderData(HttpServletRequest request, Object data) {
		
	}
	
}
